package com.app.micaihu.view.main.game.adapter;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.text.ClipboardManager;
import android.text.Html;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.base.AppBaseAdapter;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.bean.comment.NewsComment;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.GoodView.GoodView;
import com.app.micaihu.custom.view.RatingBarView;
import com.app.micaihu.custom.view.dialog.ReportDialog;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.CommentListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.CommentUtils;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.utils.InteractiveUtils;
import com.app.micaihu.view.comment.SecondaryCommentDetailActivity;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.view.expression.view.BiaoQinTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Guo on 2017/3/14.
 */

public class GameCommentAdapter extends AppBaseAdapter<NewsComment> implements View.OnClickListener {
    private GoodView mGoodView;//点赞PopupWindow
    private CommentListener commentListener;//评论监听
    //菜单弹窗
    private PopupWindow menuPopwin;//菜单弹窗
    private View upView;//菜单弹窗上面箭头
    private View downView;//菜单弹窗下面箭头
    private View deleteView;//删除按钮
    private View deleteLineView;//删除按钮的线
    private int menuViewWidth;//菜单弹窗宽度
    private int menuViewHeight;//菜单弹窗高度

    //逻辑数据
    private NewsComment currentMenuComment;//当前操作的评论
    private NewsComment currentReplyComment;//当前进行回复的评论
    public NewsComment currenZanComment;//当前进行点赞的评论
    public int currentLastHotIndex;//当前最后一个热门评论的下标
    public String replyColor;//回复颜色

    public static List<String> zanList;//点赞集合


    public GameCommentAdapter(List<NewsComment> list, Activity activity) {
        super(list, activity);
        replyColor = "#546a93";
    }

    public static List<String> getZanList() {
        if (zanList == null) {
            String sql = "select * from " + NewsDBSqlHelper.COMMENT_ZAN;
            zanList = NewsDBUtil.getInstance().getListID(sql);
        }
        return zanList;
    }


    @Override
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public int getItemViewType(int position) {
        NewsComment newsComment = list.get(position);
        if (newsComment == null) {
            return 0;
        }
        if (!TextUtils.isEmpty(newsComment.getCommentTypeName())) {
            //如果typename不为空则表示 此评论是代码加入的
            return 1;
        } else {
            return 2;
        }
    }

    @Override
    public View creatView(int position, View convertView, ViewGroup parent) {
        GameCommentAdapter.ViewHolder viewHolder;
        int type = getItemViewType(position);
        if (convertView == null) {

            if (type == 2) {
                convertView = inflater.inflate(R.layout.item_news_comment_game, null);
                viewHolder = new GameCommentAdapter.ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else if (type == 1) {
                convertView = inflater.inflate(R.layout.layout_driver_title_margin_game, null);
                ((TextView) (convertView.findViewById(android.R.id.text2))).setText(list.get(position).getCommentTypeName());
                return convertView;
            } else {
                convertView = inflater.inflate(R.layout.item_layout_gone, null);
                return convertView;
            }

        } else {
            if (type == 2) {
                viewHolder = (GameCommentAdapter.ViewHolder) convertView.getTag();
            } else if (type == 1) {
                ((TextView) (convertView.findViewById(android.R.id.text2))).setText(list.get(position).getCommentTypeName());
                return convertView;
            } else {
                return convertView;
            }
        }
        NewsComment newsComment = list.get(position);

        if (newsComment == null) {
            return convertView;
        }

        if (position == currentLastHotIndex) {
            viewHolder.lineview.setVisibility(View.INVISIBLE);
        } else if (viewHolder.lineview.getVisibility() == View.INVISIBLE) {
            viewHolder.lineview.setVisibility(View.VISIBLE);
        }
        viewHolder.parentLayout.setTag(R.id.tag_first, newsComment);//设置数据标识
        viewHolder.replyLayout.setTag(newsComment);//设置数据标识
        viewHolder.readAllText.setTag(newsComment);
        viewHolder.userImg.setTag(newsComment);
        viewHolder.userName.setTag(newsComment);
        viewHolder.parentLayout.setTag(R.id.tag_first, newsComment);


        viewHolder.rabStar.setStar(StringUtils.toFloat(newsComment.getStar(), 0.0f));


        //TODO 暂时替代 评论列表卡顿
//        LoadImageUtils.getInstance().loadCircleImage(viewHolder.userImg, newsComment.getHeadPic());
        LoadImageUtils.getInstance().loadListCircleImage(viewHolder.userImg, newsComment.getHeadPic());
//        LoadImageUtils.getInstance().loadImage(viewHolder.userRank, newsComment.getRankIcon());

        ImageLoadUtils.loadImage(newsComment.getRankIcon(), viewHolder.userRank);
        if (com.blankj.utilcode.util.StringUtils.isEmpty(newsComment.getHonourPic())) {
            viewHolder.ivHonourPic.setVisibility(View.GONE);
        } else {
            viewHolder.ivHonourPic.setVisibility(View.VISIBLE);
            ImageLoadUtils.loadImage(newsComment.getHonourPic(), viewHolder.ivHonourPic);
        }


        viewHolder.tvArmyGroupInfo.setText(newsComment.getArmyGroupInfo());
        viewHolder.userName.setText(newsComment.getNickName());
        viewHolder.rankname.setText(newsComment.getRankName());
        viewHolder.commentTime.setText(newsComment.getPublishTime());
        viewHolder.commentZan.setText((TextUtils.isEmpty(newsComment.getPraiseNum()) || TextUtils.equals("0", newsComment.getPraiseNum())) ? "" : newsComment.getPraiseNum());
        viewHolder.message.setPicText(newsComment.getContent());


        float measureText = viewHolder.paint.measureText(newsComment.getContent());
        if (measureText > ViewSizeUtils.getWidthPixels() * 8) {
            viewHolder.readAllText.setVisibility(View.VISIBLE);
        } else {
            viewHolder.readAllText.setVisibility(View.GONE);
        }


        //判断是否点赞过
//        if(zanList.contains(newsComment.getId())){
        if (InteractiveUtils.getInstance().theLaudIsContains(newsComment.getId(), true)
                && StringUtils.toInt(newsComment.getPraiseNum(), 0) > 0) {
            viewHolder.commentZan.setEnabled(false);
            viewHolder.laudContainer.setTag(true);
        } else {
            viewHolder.commentZan.setEnabled(true);
            viewHolder.laudContainer.setTag(newsComment);
        }
        //判断有没有子回复
        List<NewsComment> replys = list.get(position).getChildList();
        if (replys != null && replys.size() != 0) {
            viewHolder.replyLayout.removeAllViews();
            String reply_str;
            for (int i = 0; i < replys.size(); i++) {
                NewsComment reply = replys.get(i);
                if (reply == null) {
                    continue;
                }
                BiaoQinTextView textView = new BiaoQinTextView(context);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                if (i != replys.size() - 1) {
                    layoutParams.setMargins(0, 0, 0, 10);
                }
                textView.setLayoutParams(layoutParams);
                textView.setLineSpacing(4.3f, 1.1f);
                textView.setMaxLines(3);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setTextSize(15f);
                textView.setTextColor(context.getResources().getColor(R.color.comment_reply_msg));
                if (TextUtils.equals(reply.getType(), TypeConstant.COMMENT_TWO)) {
                    reply_str = "<font color='" + replyColor + "' >" + reply.getNickName() + ": @" + reply.getpNickName() + " </font>" + reply.getContent();
                } else {
                    reply_str = "<font color='" + replyColor + "' >" + reply.getNickName() + ": </font>" + reply.getContent();
                }
                textView.setPicText(Html.fromHtml(reply_str));
                viewHolder.replyLayout.addView(textView);
            }
            viewHolder.replyLayout.setVisibility(View.VISIBLE);
            if (StringUtils.toInt(newsComment.getChildNum(), 0) > 3) {
                TextView moreview = new TextView(context);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(0, 15, 0, 0);
                moreview.setLayoutParams(layoutParams);
                moreview.setTextSize(12f);
                moreview.setTextColor(context.getResources().getColor(R.color.common_font_color_8));
                moreview.setText("查看全部" + newsComment.getChildNum() + "条回复");
                viewHolder.replyLayout.addView(moreview);
            }
        } else {
            viewHolder.replyLayout.setVisibility(View.GONE);
        }

        return convertView;
    }


    /*************** 事件 start *************/
    @Override
    public void onClick(View view) {
        if (view == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.fl_laud_container://点赞
//                laud(view);
                InteractiveUtils.getInstance().laud((FrameLayout) view, null);
                break;

            case R.id.reply://菜单回复
                menuPopwin.dismiss();
                replyComment();
                break;
            case R.id.jubao://菜单举报
                menuPopwin.dismiss();
                reportComment();
                break;
            case R.id.fuzhi://菜单复制
                menuPopwin.dismiss();
                copy();
                break;
            case R.id.delete://删除评论
                menuPopwin.dismiss();
                deleteComment();
                break;
            case R.id.comment_readall://查看全文
            case R.id.comment_reply_layout://查看回复

                try {
                    currenZanComment = (NewsComment) view.getTag();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (currenZanComment == null) {
                    return;
                }
                Intent intent = new Intent(context, SecondaryCommentDetailActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, currenZanComment.getArticleId());
                intent.putExtra(Config.Extra.PARAMETER2, currenZanComment.getId());
                ((Activity) context).startActivityForResult(intent, Config.ResultCode.REQUESTCODE_1);
                break;
            case R.id.comment_parentlayout://点击父布局弹出菜单框
                try {
                    currenZanComment = (NewsComment) view.getTag(R.id.tag_first);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (currenZanComment == null) {
                    return;
                }
                Intent intent2 = new Intent(context, SecondaryCommentDetailActivity.class);
                intent2.putExtra(Config.Extra.PARAMETER1, currenZanComment.getArticleId());
                intent2.putExtra(Config.Extra.PARAMETER2, currenZanComment.getId());
                ((Activity) context).startActivityForResult(intent2, Config.ResultCode.REQUESTCODE_1);
                break;

            case R.id.comment_username://点击名字
            case R.id.comment_usericon://点击头像
                NewsComment newsComment1 = null;
                try {
                    newsComment1 = (NewsComment) view.getTag();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (newsComment1 == null) {
                    return;
                }
                Intent intent1 = new Intent(context, MyHomepageDynamicActivity.class);
                intent1.putExtra(Config.Extra.PARAMETER1, newsComment1.getUid());
                context.startActivity(intent1);
                break;
            default:
                break;
        }
    }

    /**
     * 通知点赞变化
     */
    public void notifyZanComment() {
        if (currenZanComment != null) {
//            String praiseNum = currenZanComment.getPraiseNum();
            int zan = StringUtils.toInt(currenZanComment.getPraiseNum(), 0) + 1;
            currenZanComment.setPraiseNum(zan + "");
//            zanList.add(currenZanComment.getId());
            notifyDataSetChanged();
        }
    }


    /**
     * 回复评论
     */
    private void replyComment() {
        if (currentMenuComment == null) {
            return;
        }
        if (commentListener == null) {
            commentListener = new CommentListener() {
                @Override
                public void commentStart() {

                }

                @Override
                public void commentFail(VolleyError volley) {

                }

                @Override
                public void commentSuccess(NewsComment newsComment) {
                    if (currentReplyComment == null) {
                        return;
                    }
                    List<NewsComment> replys = currentReplyComment.getChildList();
                    if (replys == null) {
                        replys = new ArrayList<NewsComment>();
                    }
                    replys.add(newsComment);
                    notifyDataSetChanged();
                }
            };
        }
        currentReplyComment = currentMenuComment;
        CommentUtils.getInstance().showDialog((Activity) context, null, currentReplyComment.getArticleId(), currentMenuComment, commentListener);
    }

    /**
     * 复制
     */
    private void copy() {
        if (currentMenuComment != null) {
            String content = currentMenuComment.getContent();
            if (TextUtils.isEmpty(content) || context == null) {
                ToastUtils.makeText("复制失败");
                return;
            }
            // 得到剪贴板管理器
            ClipboardManager cmb = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(content.trim());
            ToastUtils.makeText("已复制");
        }
    }

    /**
     * 删除评论
     */
    private void deleteComment() {

        final NewsComment deleteComt = currentMenuComment;
        CommentListener deleteComtListener = new CommentListener() {
            @Override
            public void commentStart() {

            }

            @Override
            public void commentFail(VolleyError volley) {

            }

            @Override
            public void commentSuccess(NewsComment newsComment) {
                if (deleteComt == null) {
                    return;
                }
                list.remove(deleteComt);
                notifyDataSetChanged();
            }
        };
        CommentUtils.getInstance().showDeleteDialog((Activity) context, deleteComt, deleteComtListener, false);

    }


    ReportDialog reportDialog;

    /**
     * 举报
     */
    private void reportComment() {
        if (currentMenuComment == null) {
            ToastUtils.makeText("举报失败,请稍后重试");
            return;
        }

        final String id = currentMenuComment.getId() + "";
        String sql = "select * from " + NewsDBSqlHelper.COMMENT_REPORT + "where _id=" + id;
        boolean isReport = NewsDBUtil.getInstance().hasDataBySql(sql);
        if (isReport) {
            ToastUtils.makeText("您已经举报过该评论了");
            return;
        } else {
            if (reportDialog == null) {
                reportDialog = new ReportDialog((Activity) context);
            }
            String comid = null;
            if (currentMenuComment != null) {
                comid = currentMenuComment.getId();
            }
//            reportDialog.show(comid,false);
            reportDialog.show(comid, TypeConstant.PAGE_COMMENT, TypeConstant.JUBAO_COMMENT_PARENT);
        }

    }

    /**
     * 点赞
     * @param view
     */
//    private void laud(final View view){
//
//        if(Boolean.valueOf(view.getTag().toString())){
//            ToastUtils.makeText("您已经赞过");
//            return;
//        }
//        //提前改变点赞效果以及点赞成功数据(点赞伪成功)
//        final NewsComment cm = (NewsComment) view.getTag();
//
//        final TextView tv =(TextView) view;
//
//        //请求点赞网络操作
//        ParamMap parmsMap = new ParamMap();
//        if(UserInforManager.getInstance().isLogin()){
//            parmsMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
//        }else{
//            parmsMap.putEncode("uid", "0");
//        }
//        parmsMap.putEncode("type", "1");
//        parmsMap.putEncode("articleId", cm.getArticleId());
//        parmsMap.putEncode("toUid", cm.getUid());
//        parmsMap.putEncode("commentId", cm.getId());
//        parmsMap.putEncode("operateType", "0");
//        parmsMap.putEncode("parentCmtId", cm.getParentCmtId());
//        HttpUtils.ParmsMapMD5(parmsMap);
//
//        HttpListener<DataBean> httpListener = new HttpListener<DataBean>() {
//            @Override
//            public void onError(VolleyError error) {
//            }
//
//            @Override
//            public void onSuccess(DataBean response) {
//                if(response.noError()){
//                    view.setSelected(true);
//                    String zanNum = (StringUtils.toInt(tv.getText().toString(), 0) + 1)+"";
//                    tv.setText(zanNum);
//                    cm.setPraiseNum(zanNum);
//                    if(mGoodView == null){
//                        mGoodView = new GoodView(context);
//                    }
//                    mGoodView.setTextInfo("+1", Color.parseColor("#e55d5d"), 12);
//                    mGoodView.show(view);
//                    view.setTag(true);
////                    String sql = "insert into "+NewsDBSqlHelper.COMMENT_ZAN+" values ("+cm.getId()+")";
////                    NewsDBUtil.getInstance().changeData(sql);
//
//                    InteractiveUtils.getInstance().publicInsertLaudIdToMemory(cm.getId());
//                }
//            }
//        };
//
//        //请求网络
//        HttpUtils.addPostRequest(URIContant.NEWS_ZAN, new TypeToken<DataBean>() {
//        }.getType(), null, parmsMap, httpListener);
//    }

    /**
     * 展示菜单弹窗
     *
     * @param view
     */
    private void showMenuPop(View view) {
        if (menuPopwin == null) {
            initPopmenu();//初始化菜单弹窗
            menuViewWidth = ViewSizeUtils.getViewW(menuPopwin.getContentView());
            menuViewHeight = ViewSizeUtils.getViewH(menuPopwin.getContentView());
        }
        if (!menuPopwin.isShowing() && !((Activity) context).isFinishing()) {
            currentMenuComment = (NewsComment) view.getTag(R.id.tag_first);
            int[] locations = new int[2];
            view.getLocationOnScreen(locations);
            int x = (ViewSizeUtils.getWidthPixels() - menuViewWidth) / 2;
            int y = 0;
            //item的纵坐标的位置判断menuPopwin显示的高度位置
            if (locations[1] <= ViewSizeUtils.getHeightPixels() * 1 / 3) {
                y = -menuViewHeight / 2;
                upView.setVisibility(View.VISIBLE);
                downView.setVisibility(View.GONE);
            } else {
                y = -(view.getHeight() + menuViewHeight / 2) + ViewSizeUtils.getViewH(upView);
                upView.setVisibility(View.GONE);
                downView.setVisibility(View.VISIBLE);
            }
            if (UserInforManager.getInstance().isLogin() &&
                    TextUtils.equals(UserInforManager.getInstance().getUserInfor().getUid(), currentMenuComment.getUid())
                    && deleteView != null) {
                //如果当前评论的作者就是用户本人则显示删除按钮
                deleteView.setVisibility(View.VISIBLE);
                deleteLineView.setVisibility(View.VISIBLE);
            } else if (deleteView != null) {
                deleteView.setVisibility(View.GONE);
                deleteLineView.setVisibility(View.GONE);
            }
            try {
                if (!((Activity) context).isFinishing()) {
                    menuPopwin.showAsDropDown(view, x, y);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化菜单弹窗
     */
    private void initPopmenu() {
        View view = inflater.inflate(R.layout.popwin_comment_menu, null);
        View reply = view.findViewById(R.id.reply);
        View jubao = view.findViewById(R.id.jubao);
        View fuzhi = view.findViewById(R.id.fuzhi);
        deleteView = view.findViewById(R.id.delete);
        deleteLineView = view.findViewById(R.id.delete_line);
        upView = view.findViewById(R.id.jiantou_up);
        downView = view.findViewById(R.id.jiantou_down);
        reply.setOnClickListener(this);
        jubao.setOnClickListener(this);
        fuzhi.setOnClickListener(this);
        deleteView.setOnClickListener(this);
        menuPopwin = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        menuPopwin.setBackgroundDrawable(new BitmapDrawable());
        menuPopwin.setOutsideTouchable(true);
        menuPopwin.setFocusable(true);
        menuPopwin.setAnimationStyle(R.style.comment_menu_PopupAnimation);
    }

//    @Override
//    public boolean onPreDraw() {
//        return false;
//    }


    private class ViewHolder implements View.OnLongClickListener {

        CustomImageView userImg;//头像
        CustomImageView userRank;//军衔
        ImageView ivHonourPic;//粉絲標志
        TextView userName;//名称
        TextView tvArmyGroupInfo;//名称
        TextView rankname;//军衔名称
        TextView commentZan;//点赞
        TextView commentTime;//发布时间
        BiaoQinTextView message;//评论内容
        LinearLayout replyLayout;//评论回复模块
        TextView readAllText;//查看全文
        View parentLayout;//父布局
        View lineview;//下划线
        FrameLayout laudContainer;//点赞 的点击

        RatingBarView rabStar;


        TextPaint paint;

        public ViewHolder(View convertView) {
            parentLayout = convertView.findViewById(R.id.comment_parentlayout);
            userImg = (CustomImageView) convertView.findViewById(R.id.comment_usericon);
            userName = (TextView) convertView.findViewById(R.id.comment_username);
            userRank = (CustomImageView) convertView.findViewById(R.id.comment_rank);
            ivHonourPic = convertView.findViewById(R.id.ivHonourPic);
            tvArmyGroupInfo = convertView.findViewById(R.id.tvArmyGroupInfo);
            rankname = (TextView) convertView.findViewById(R.id.comment_rank_name);
            commentTime = (TextView) convertView.findViewById(R.id.comment_time);
            commentZan = (TextView) convertView.findViewById(R.id.comment_zan);
            laudContainer = (FrameLayout) convertView.findViewById(R.id.fl_laud_container);
            message = (BiaoQinTextView) convertView.findViewById(R.id.comment_message);
            replyLayout = (LinearLayout) convertView.findViewById(R.id.comment_reply_layout);
            readAllText = (TextView) convertView.findViewById(R.id.comment_readall);
            lineview = convertView.findViewById(R.id.item_divider);
            rabStar = (RatingBarView) convertView.findViewById(R.id.rbv_star);
            replyLayout.setOnClickListener(GameCommentAdapter.this);
            parentLayout.setOnClickListener(GameCommentAdapter.this);


            parentLayout.setOnLongClickListener(this);

            laudContainer.setOnClickListener(GameCommentAdapter.this);
            readAllText.setOnClickListener(GameCommentAdapter.this);
            userImg.setOnClickListener(GameCommentAdapter.this);
            userName.setOnClickListener(GameCommentAdapter.this);
//            ViewTreeObserver viewTreeObserver = message.getViewTreeObserver();
//            viewTreeObserver.addOnPreDrawListener(this);

            paint = message.getPaint();
        }

//        @Override
//        public boolean onPreDraw() {
//            int width = message.getWidth();
//            TextPaint paint = message.getPaint();
//            float measureText = paint.measureText(message.getText().toString());
//            if (measureText > width * 8) {
//                readAllText.setVisibility(View.VISIBLE);
//            } else {
//                readAllText.setVisibility(View.GONE);
//            }
//            return true;
//        }

        @Override
        public boolean onLongClick(View v) {
            if (v != null) {
                if (v.getId() == R.id.comment_parentlayout) {
                    showMenuPop(v);
                    return true;
                }
            }
            return false;
        }
    }
}
